import React from 'react';
import './style.less';

class Demo extends React.Component{
    constructor(props){
        super(props)
        this.state =  {
            delta: [0, 0],
            isPressed: false,
            left:100
        };
        this.pressPos = [0,0];

        window.addEventListener('touchmove', this.handleTouchMove.bind(this));
        window.addEventListener('touchend', this.handleMouseUp.bind(this));
        window.addEventListener('mousemove', this.handleMouseMove.bind(this));
        window.addEventListener('mouseup', this.handleMouseUp.bind(this));
    }
    componentWillUnmount(){
        window.removeEventListener('touchmove', this.handleTouchMove.bind(this));
        window.removeEventListener('touchend', this.handleMouseUp.bind(this));
        window.removeEventListener('mousemove', this.handleMouseMove.bind(this));
        window.removeEventListener('mouseup', this.handleMouseUp.bind(this));
    }

    handleTouchStart(e) {
        this.handleMouseDown(e.touches[0]);
    }
    handleMouseDown({pageX, pageY}) {
        this.setState({
            isPressed: true,
            delta:[0, 0],
        });
        this.pressPos = [pageX, pageY];
    }

    handleMouseMove({pageX, pageY}) {
        const {isPressed} = this.state;
        let [px,py] = this.pressPos
        if (isPressed) {
            const delta = [pageX - px  , pageY - py];
            this.setState({delta});
        }
    }
    handleTouchMove(e) {
        e.preventDefault();
        this.handleMouseMove(e.touches[0]);
    }
    handleMouseUp() {
        this.pressPos = [0, 0];
        let left = this.state.left + this.state.delta[0];
        left = this.state.left;
        this.setState({left,isPressed: false, delta: [0, 0]});
    }
    render(){
        const { isPressed, delta} = this.state;
        let style;
        if (isPressed) {
            style = {
                left:this.state.left + delta[0]
            }
        }else{
            style = {
                left:this.state.left
            }
        }

        return(
            <div className="card">
                <Button>111</Button>
                <div className="inner" style={style}
                     onMouseDown={this.handleMouseDown.bind(this)}
                     onTouchStart={this.handleTouchStart.bind(this)}
                >

                </div>
            </div>
        )
    }
}
export default Demo;